package com.yanghui.dtracing.plugin.mysql;

import com.mysql.cj.ClientPreparedQuery;
import com.mysql.cj.NativeSession;
import com.mysql.cj.Query;
import com.mysql.cj.jdbc.ClientPreparedStatement;
import com.yanghui.dtracing.core.constant.TypeEnum;
import com.yanghui.dtracing.core.opentracing.DTracerTags;
import com.yanghui.dtracing.core.plugin.interceptor.AbstractInstanceMethodInterceptor;
import com.yanghui.dtracing.core.plugin.interceptor.MethodInterceptResult;
import io.opentracing.Span;
import io.opentracing.tag.Tags;

import java.lang.reflect.Method;

public class MysqlInstanceMethodAroundInterceptor extends AbstractInstanceMethodInterceptor {

    @Override
    protected void doBeforeMethod(Object thisObj, Method method, Object[] allArguments, MethodInterceptResult result, Span span) throws Throwable {
        NativeSession connection = (NativeSession)thisObj;
        String hostPort = connection.getHostInfo().getHostPortPair();


        span.setTag(Tags.SPAN_KIND,Tags.SPAN_KIND_CLIENT)
                .setTag(Tags.COMPONENT, DTracerTags.COMPONENT_MYSQL)
                .setTag(Tags.DB_INSTANCE,hostPort)
                .setTag(Tags.DB_TYPE,DTracerTags.DB_TYPE_SQL)
                .setTag(Tags.DB_STATEMENT,getSql(allArguments))
                .setTag(DTracerTags.TYPE, TypeEnum.EXIT.getName());
    }

    private String getSql(Object[] allArguments){
        Object one = allArguments[0];
        if(null == one){
            return allArguments[1] != null ? allArguments[1].toString() : "not sql";
        }
        if(allArguments[0] instanceof ClientPreparedStatement){
            ClientPreparedStatement statement = (ClientPreparedStatement)allArguments[0];
            if(statement.getQuery() instanceof ClientPreparedQuery){
                ClientPreparedQuery query = (ClientPreparedQuery)statement.getQuery();
                return query.getOriginalSql();
            }
        }
        return "not sql";
    }
}
